import re
from urllib import request


# 断点调试
# \d \D
# \w 单词字符 \W 非单词字符
# \s 空白字符 \S 非空白字符   [\s\S]代表所以字符
# . 匹配除换行符\n之外其它所有字符
# * 一次或多次
# ？非贪婪模式

class Spider():
    url = 'https://www.huya.com/g/lol'
    root_pattern = '<span class="txt">([\s\S]*)</span>'  # [\s\S]*?
    name_pattern='<i class="nick" title="([\s\S]*?)">'
    number_pattern='<span class="num"><i class="num-icon"></i><i class="js-num">([\s\S]*?)</i></span>'


    # 加两个'__'是私有方法
    def __fetch_content(self):
        r = request.urlopen(Spider.url)
        htmls = r.read()
        htmls = str(htmls, encoding='utf-8')
        return htmls

        a = 21


    def __analysis(self, htmls):
        root_html = re.findall(Spider.root_pattern, htmls)
        anchors = []
        for html in root_html:
            name=re.findall(Spider.name_pattern,html)
            number=re.findall(Spider.number_pattern,html)
            anchor={'name':name,'number':number}
            anchors.append(anchor)
        return anchors
        a=1

    def __refine(self,anchors):
    #     l= lambda anchor:{
    #         'name':anchor['name'][0].strip(),
    #         'number':anchor['number'][0]
    #     }
        return list(anchors)

    def __sort(self,anchors):
        anchors=sorted(anchors,key=self.__sort_seed)
        return anchors

    def __sort_seed(self,anchor):
        return anchor['number']

    def __show(self,anchors):
        for anchor in anchors:
            # print(anchor['name'] + '----' + anchor['number'])
            print(anchor['name'])
            print('\n')
            print(anchor['number'])



    def go(self):
        htmls=self.__fetch_content()
        anchors=self.__analysis(htmls)
        anchors=self.__refine(anchors)
        anchors=self.__sort(anchors)
        anchors=self.__show(anchors)

        print(anchors)


spider = Spider()
spider.go()
